﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.MVC.App_Start;

namespace App.MVC.Controllers
{
    public class UploadController : Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }
        ///   <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Upload()
        {
            string fileName = Request["name"];

            var dir = Server.MapPath("~/Upload/" + SiteInfo.GetUserName());
            int lastIndex = fileName.LastIndexOf('.');
            string extendRelName = fileName.Substring(lastIndex);
            string fileRelName = lastIndex == -1 ? fileName : fileName.Substring(0, fileName.LastIndexOf('.'));
            fileRelName = fileRelName.Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace(",", "");
            int index = Convert.ToInt32(Request["chunk"]); //当前分块序号
            var guid = Request["guid"]; //前端传来的GUID号
            //文件上传目录
            string currentTime = DateTime.Now.ToString("yyyy-MM-dd");
            dir += "\\" + currentTime;
            //dir = Path.Combine(dir, fileRelName);//临时保存分块的目录

            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            string newfilename = GetTimestamp(DateTime.Now) + extendRelName;
            string filePath = Path.Combine(dir, newfilename);//分块文件名为索引名，更严谨一些可以加上是否存在的判断，防止多线程时并发冲突
            var data = Request.Files["file"];
            //表单中取得分块文件
            //if (data != null)//为null可能是暂停的那一瞬间
            //{
            data.SaveAs(filePath);//报错
            //}
            var flag = false;

            #region 检测是否是重复文件
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(dir);
            var uploadfileHash = Verification.GetFileHash(filePath);
            var oldfilename = string.Empty;
            var oldfilepath = string.Empty;
            foreach (System.IO.FileInfo file in directory.GetFiles())
            {
                if (uploadfileHash == Verification.GetFileHash((file.DirectoryName + @"\" + file.Name)) && file.Name != newfilename)
                {
                    flag = true;
                    oldfilename = file.Name;
                    oldfilepath = file.DirectoryName;
                    break;
                }
            }

            if (flag)
            {
                System.IO.FileInfo file = new FileInfo(filePath);
                file.Delete();
                return Json(new { name = oldfilename, filepath = "/" + oldfilepath.Substring(dir.IndexOf("Upload", StringComparison.Ordinal)).Replace(@"\", "/") });
            }
            #endregion

            return Json(new { name = newfilename, filepath = "/"+dir.Substring(dir.IndexOf("Upload", StringComparison.Ordinal)).Replace(@"\","/") , uploadfileHash = uploadfileHash });//Demo，随便返回了个值，请勿参考
        }

        public JsonResult Merge(string guid, string filename, string filePath)
        {
            dynamic data = new { filename = filename, filepath = filePath };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public long GetTimestamp(DateTime dateTime)
        {
            return (dateTime.Ticks - 621355968000000000) / 10000;
        }

        public DateTime NewDate(long timestamp)
        {
            long tt = 621355968000000000 + timestamp * 10000; return new DateTime(tt);
        }

        //
        //directory.Empty();

    }
}